package com.redwine.app.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.redwine.app.APP;
import com.redwine.app.R;
import com.redwine.app.chat.ChatActivity;
import com.redwine.app.chat.ChatConstant;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.MessageListResponse;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.AlertDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息列表适配器
 * 作者：gassion on 17/8/26 17:06
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MessageAdapter extends BaseAdapter {

    private Context mContext;

    private List<MessageListResponse.DataEntity> datalist;


    public MessageAdapter(Context context) {
        this.mContext = context;
    }


    /**
     * 下拉加载数据
     *
     * @param datalist
     */
    public void setData(List<MessageListResponse.DataEntity> datalist) {
        this.datalist = datalist;
        notifyDataSetChanged();
    }

    public List<MessageListResponse.DataEntity> getData() {
        if (null != datalist && !datalist.isEmpty()) {
            return datalist;
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public int getCount() {
        if (null != datalist) {
            return datalist.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        if (null != datalist) {
            return datalist.get(position);
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            convertView = layoutInflater.inflate(R.layout.activity_message_item, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final MessageListResponse.DataEntity dataEntity = datalist.get(position);
        BitmapUtils.loadImage(viewHolder.messageIvUserIcon, dataEntity.getAvatar(), BitmapUtils.ROUND);
        viewHolder.messageTvUserName.setText(dataEntity.getNickname());
        viewHolder.messageTvTime.setText(dataEntity.getDate());
        viewHolder.messageTvContent.setText("聊天的内容");
        viewHolder.messageTvContent.setVisibility(View.INVISIBLE);
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(mContext.getString(R.string.hint));
                builder.setMessage(mContext.getString(R.string.sure_to_delete_the_contact));
                builder.setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestDelContact(dataEntity.getFriend_uid(), position);
                    }
                });
                AlertDialog mDialog = builder.create();
                mDialog.setCancelable(false);
                mDialog.show();
                return false;
            }
        });
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ChatActivity.class);
                intent.putExtra(ChatConstant.EXTRA_USER_NICK_NAME, dataEntity.getNickname());
                intent.putExtra(ChatConstant.EXTRA_USER_ID, dataEntity.getUid());
                intent.putExtra(ChatConstant.EXTRA_USER_AVATAR, dataEntity.getAvatar());
                mContext.startActivity(intent);
            }
        });
        return convertView;
    }


    public static class ViewHolder {
        public View rootView;
        public ImageView messageIvUserIcon;
        public TextView messageTvUserName;
        public TextView messageTvTime;
        public TextView messageTvContent;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.messageIvUserIcon = (ImageView) rootView.findViewById(R.id.message_iv_user_icon);
            this.messageTvUserName = (TextView) rootView.findViewById(R.id.message_tv_user_name);
            this.messageTvTime = (TextView) rootView.findViewById(R.id.message_tv_time);
            this.messageTvContent = (TextView) rootView.findViewById(R.id.message_tv_content);
        }

    }

    private void requestDelContact(final String friend_uid, final int position) {
        String url = NetworkConstants.FRIEND_DEL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("friend_uid", friend_uid);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                Utils.showToast(response.getMsg());
                if (response.isSuccess()) {
                    datalist.remove(position);
                    notifyDataSetChanged();
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(friend_uid, EaseCommonUtils.getConversationType(EaseConstant.CHATTYPE_SINGLE), true);
                    if (null != conversation)
                        conversation.clearAllMessages();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }
}
